// pages/celiang/celiang.js

var api = require('../../js/api.js')
var utilBT = require('../../js/utilBT.js');
var utilH = require('../../js/utilHeart.js');
var utilAudio = require('../../js/utilAudio.js');

const app = getApp()

let oldele = 0
let heart = 0
let dcolor = 'green'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        color: ['#F1435C', '#4BAC51', '#03CE96', '#07957C', '#FAB659', '#FD764D'],

        equ_name: 0,
        playaudio: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        utilH.countMaxHeart()
        // this.canvasdDraw(0)
        this.canvas0Draw(1, '---', '未连接到设备')
        if (!app.globalData.head.noToken) {
            if (app.globalData.equ == null || app.globalData.equ.name == '' || app.globalData.equ.deviceId == '') {
                wx.showModal({
                    title: '未绑定设备',
                    content: '请到个人中心-设备连接页面进行设备的连接和绑定',
                })
            }
        }

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this
        if (app.globalData.equ.name == 'RecoveryPlusH1' || app.globalData.equ.name == 'RecoveryPlusH2'){
            that.setData({
                equ_name: 1
            })
        }


        that.playAudio()

        that.receiveData()
        console.log('================>>><<<<========')
        console.log('==>>name：' + that.data.equ_name)
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

        var that = this
        clearInterval(that.data.playaudio)
        that.setData({
            playaudio: 0
        })

        wx.offBLECharacteristicValueChange(function (res) {
            console.log('====>>取消监听蓝牙数据')
            console.log(res)
            heart = 0
        })

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        oldele = 0
        heart = 0
        dcolor = 'green'
        utilBT.closeconn(app.globalData.equ.deviceId)
        this.onLoad()
        wx.stopPullDownRefresh()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    yuyin: function () {
    },
    canvas0Draw: function (index, heart, msg) {

        var that = this

        const query = wx.createSelectorQuery().select('#canvas0')
            .fields({node: true, size: true})
            .exec((res) => {
                // console.log(res)
                const canvas = res[0].node

                const ctx = canvas.getContext('2d')

                canvas.width = 1000;
                canvas.height = 1000;
                ctx.clearRect(0, 0, 1000, 1000);


                ctx.beginPath()
                let img = canvas.createImage()
                img.src = '/img/xl-xin.png';

                img.onload = () => {
                    ctx.drawImage(img, 560, 370, 60, 60)
                }

                ctx.font = '140px Defult'
                ctx.fillStyle = 'black'
                ctx.textAlign = 'end'
                ctx.fillText(heart, 530, 480)

                ctx.font = '50px Defult'
                ctx.fillStyle = 'black'
                ctx.textAlign = 'start'
                ctx.fillText('BPM', 560, 480)

                ctx.font = '40px Georgia'
                ctx.fillStyle = 'black'
                ctx.textAlign = 'center'
                ctx.fillText(msg, 500, 550)

                ctx.closePath()

                for (let i = 0; i < 6; i++) {
                    let x = 500
                    let y = 500
                    let r = 330
                    let w = 60
                    if (index == i) {
                        r = 310
                        w = 100
                    }
                    ctx.beginPath()
                    ctx.arc(x, y, r, (i / 3 + 0.005) * Math.PI, ((i + 1) / 3 - 0.005) * Math.PI, false)
                    ctx.strokeStyle = that.data.color[i]
                    // ctx.fillStyle = that.data.color[i]
                    ctx.lineWidth = w
                    ctx.stroke()
                    ctx.closePath()

                }


            })
    },
    canvasdDraw: function (electric) {

        console.log('==>>电量：' + electric)
        var that = this

        if (electric <= 20) {
            dcolor = 'red'
        } else {
            dcolor = 'green'
        }

        wx.createSelectorQuery()
            .select('#canvasd')
            .fields({node: true, size: true})
            .exec((res) => {
                // console.log(res)
                const canvas = res[0].node
                const ctx = canvas.getContext('2d')

                canvas.width = 1000;
                canvas.height = 70;
                ctx.clearRect(0, 0, 1000, 70);


                ctx.beginPath()
                ctx.strokeStyle = '#000000'
                ctx.strokeRect(100, 10, 100, 50)
                ctx.stroke()
                // ctx.closePath()
                //
                // ctx.beginPath()
                ctx.fillStyle = '#000000'
                ctx.fillRect(202, 20, 10, 30)
                ctx.fill()
                // ctx.closePath()
                //
                // ctx.beginPath()
                ctx.fillStyle = dcolor
                ctx.fillRect(100, 10, electric, 50)
                ctx.fill()
                // ctx.closePath()
                //
                // ctx.beginPath()
                ctx.font = '40px Defult'
                ctx.fillStyle = dcolor
                ctx.fillText(electric + '%', 230, 50)
                ctx.closePath()


            })
    },

    receiveData: function () {
        console.log('==>>开始接收数据')
        var that = this
        wx.onBLECharacteristicValueChange(function (res) {
            console.log('====>>' + app.globalData.equ.name + '接收到的数据')
            console.log(res)
            let data = new Uint8Array(res.value)
            console.log(JSON.stringify(data))
            console.log('==>>心率：' + data[1])
            // if (data[1] < 25) {
            //     console.log('====>>心率太低')
            //     utilBT.closeconn(app.globalData.equ.deviceId)
            //     // that.canvas0Draw(1, '---', '未连接到设备')
            //     // utilAudio.audioPlay(app.globalData.audio.connfail)
            // } else if (data[1] > 0) {
                heart = data[1]
                utilH.getIndex(data[1], function (res) {
                    that.canvas0Draw(res[0], data[1], res[1])
                })
                if (oldele != data[3]) {
                    oldele = data[3]
                    that.canvasdDraw(oldele)
                }
                api.saveHearts(data[1])
            // }


        })
    },
    playAudio: function () {
        var that = this
        if (that.data.playaudio == 0) {
            that.data.playaudio = setInterval(function () {
                const pages = getCurrentPages();
                const currentPage = pages[pages.length - 1];
                const url = `/${currentPage.route}`;
                if (url == '/pages/celiang/celiang' && app.globalData.audio.open && heart > 110) {
                    if (heart > 0 && heart < app.globalData.aim.aim_min) {
                        utilAudio.audioPlay(app.globalData.audio.speedlt)
                    } else if (heart > app.globalData.aim.aim_max) {
                        utilAudio.audioPlay(app.globalData.audio.speedgt)
                    } else if (heart > app.globalData.aim.aim_min && heart < app.globalData.aim.aim_max) {
                        utilAudio.audioPlay(app.globalData.audio.speedeq)
                    }

                    heart = 0

                }

            }, 30000)
        }

    },


})
